package gateway.server.lifecycle;

import gateway.api.engine.Engine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jin Zheng
 * @since 1.0 2020-09-25
 */
public class LiftCycleFactory
{
	private static Logger logger = LoggerFactory.getLogger(LiftCycleFactory.class);

	private final Engine engine;
	private final List<Lifecycle> lifecycleList = new ArrayList<>();
	private final Lifecycle initializingLifeCycle = new InitializingLifecycle();
	private final Lifecycle disposableLifeCycle = new DisposableLifecycle();

	public LiftCycleFactory(Engine engine)
	{
		this.engine = engine;
		lifecycleList.add(new EngineLifecycle(engine));
		lifecycleList.add(new ExecutorServiceLifecycle(engine));
		lifecycleList.add(new HttpClientLifecycle(engine));
	}

	public void setAware(Object target)
	{
		for (Lifecycle cycle : lifecycleList)
		{
			if (cycle.accepted(target))
			{
				this.handle(cycle, target);
			}
		}
	}

	public void initialize(Object target)
	{
		if (initializingLifeCycle.accepted(target))
		{
			this.handle(initializingLifeCycle, target);
		}
	}

	public void destroy(Object target)
	{
		if (disposableLifeCycle.accepted(target))
		{
			this.handle(disposableLifeCycle, target);
		}
	}

	private void handle(Lifecycle cycle, Object target)
	{
		try
		{
			cycle.handle(target);
		}
		catch (Exception e)
		{
			logger.error("Error, ", e);
		}
	}

}
